﻿<%@ Page Title="" Language="C#" MasterPageFile="~/default-interno.master" AutoEventWireup="true" CodeBehind="calendario.aspx.cs" Inherits="CeA.Reports.Atendimento.Web.admin.calendario" %>
<%@ Register src="../inc/WebControls/MenuInterno.ascx" tagname="MenuInterno" tagprefix="menu" %>
<asp:Content ID="head" ContentPlaceHolderID="head" runat="server">
  <link rel="Stylesheet" href="/css/jquery-fullcalendar.css" type="text/css" />
  <link rel="Stylesheet" href="/css/jquery-fullcalendar-theme.css" type="text/css" />
  <link rel="Stylesheet" href="/css/theme.css" type="text/css" />
  
  <script type="text/javascript" src="/js/jquery-ui-custom.js"></script>
  <script type="text/javascript" src="/js/jquery.fullcalendar.min.js"></script>
  
  <script type="text/javascript">
    var d = new Date();
    var y = d.getFullYear();
    var m = d.getMonth();


    function ajaxFailed(result) {
      // TODO: Modificar isso para utilizar algum mecanismo mais 
      // elegante para reportar erros do servidor
      
      alert("Erro durante a Requisição:\n" + result.status + ' ' + result.statusText);
    }

    /**
     * Carrega todos os eventos de Pico existentes.
     */
    function loadEvents(start, end, callback) {
      var calendarDate = $('#fullcalendar').fullCalendar('getDate');
      //alert("The current date of the calendar is " + d );
      
      $.ajax({
        type: "POST",
        url: "planejamentoservice.asmx/GetEvents",
        contentType: "application/json; charset=utf-8",
        data: "{'ano': " + calendarDate.getFullYear() + ", 'mes': " + eval(calendarDate.getMonth()+1) + "}",
        dataType: "json",
        success: function(result) {
          callback(result.d)
        },
        error: ajaxFailed
      });
    }


    /**
     * Atualiza um evento de pico para um evento de vale.
     */
    function updateEvent(clickedEvent, jsEvent, view) {
      var calendar = $('#fullcalendar');
      
      //alert('Event: ' + clickedEvent.id);
      
      calendar.fullCalendar('removeEvents', function(event) {
        if (event.id == clickedEvent.id)
          return true;
      })
      
      $('#loading').show();
      $.ajax({
        type: "POST",
        url: "planejamentoservice.asmx/UpdateEvent",
        contentType: "application/json; charset=utf-8",
        data: "{'id': " + clickedEvent.id + "}",
        dataType: "json",
        error: ajaxFailed,
        success: function(result) {
          $('#loading').hide();
          //callback(result.d)
        }
      });
      
      
      // change the border color just for fun
      //$(this).css('border-color', 'red');
    }
    
    /**
     * Cria um novo evento de pico.
     */
    function createEvent(date, allDay, jsEvent, view) {
        var calendar = $('#fullcalendar');
      
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        var hasEvents = false;

        //--
        //-- Só vai ao servidor caso não exista evento no dia Clicado.
        //--
        calendar.fullCalendar('clientEvents', function(event) {
            existingEventDate = new Date(event.start.getFullYear(), event.start.getMonth(), event.start.getDate())

            if(existingEventDate <= date && existingEventDate >= date) {
            //  alert("Evento já existente: " + event.id);
                hasEvents = true;
                return true;
            }
            
            return false;
        });

        if(!hasEvents) {
            $('#loading').show();
            $.ajax({
                type: "POST",
                url: "planejamentoservice.asmx/CreateEvent",
                contentType: "application/json; charset=utf-8",
                data: "{'ano': " + y + ", 'mes': " + m + ", 'dia':" + d +  "}",
                dataType: "json",
                error: ajaxFailed,
                success: function(result) {
                //  callback(result.d);
                    calendar.fullCalendar('renderEvent', {
                        id    :  result.d, 
                        title : 'Pico', 
                        start :  date, 
                        allDay:  true });
                    $('#loading').hide();
                }
            });
            
        }
    //  alert($.fullCalendar.formatDate(date, 'dd/MM/yyyy') + ' has been clicked!');
    }


    $(document).ready(function() {
      var myCalendar = $('#fullcalendar');
      
      $("#cboMes").val(m + 1);
      $("#cboAno").val(y);

      $("#search").click(function() {
          myCalendar.fullCalendar('gotoDate', $("#cboAno").val(), $("#cboMes").val() - 1);
      });

      myCalendar.fullCalendar({
        theme:         true,
        editable:      false,
        dayClick:      createEvent, 
        eventClick:    updateEvent,
        buttonText:    {today:    'hoje'},
        dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
        monthNames:    ['Janeiro', 'Fevereiro', 'Março',    'Abril',   'Maio',     'Junho', 
                        'Julho',   'Agosto',    'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
        
        eventDrop: function(event, delta) {
          alert(event.title + ' was moved ' + delta + ' days\n' + '(should probably update your database)');
        },

        loading: function(bool) {
          if (bool) { /*$('#fullcalendar').hide()*/; $('#loading').show(); }
          else { /*$('#fullcalendar').show(); */$('#loading').hide(); }
        },

        viewDisplay: function(view) {
          $("#cboMes").val(view.start.getMonth() + 1);
          $("#cboAno").val(view.start.getFullYear());
          
          
          //$("#message").text("The new title of the view is " + view.start);
        },
        events: loadEvents
      })
    });
  </script>
</asp:Content>

<asp:Content ID="body" ContentPlaceHolderID="FilterContentPlaceholder" runat="server">
  <h2>Calendário: Vale e Pico</h2>
  <br />
  
  <table cellpadding="0" cellspacing="0" border="0" style="">
    <tr>
      <td style="width: 50px;">
        <label for="cboAno">Período</label>
      </td>
      <td style="width: 85px">
        <select id="cboMes" class="mes-ano-select form-select" style="width: 85px;">
          <option value="1">Janeiro</option>
          <option value="2">Fevereiro</option>
          <option value="3">Março</option>
          <option value="4">Abril</option>
          <option value="5">Maio</option>
          <option value="6">Junho</option>
          <option value="7">Julho</option>
          <option value="8">Agosto</option>
          <option value="9">Setembro</option>
          <option value="10">Outubro</option>
          <option value="11">Novembro</option>
          <option value="12">Dezembro</option>
        </select>
      </td>
      <td style="width: 55px">
        <select id="cboAno" class="mes-ano-select form-select" style="width: 55px;">
          <option value="2009">2009</option>
          <option value="2010">2010</option>
          <option value="2011">2011</option>
          <option value="2012">2012</option>
          <option value="2013">2013</option>
          <option value="2014">2014</option>
          <option value="2015">2015</option>
          <option value="2016">2016</option>
        </select>
      </td>
      <td style="width: 13px">
        <input type="button" id="search" class="search-buttom" />
      </td>
      <td style="width: auto">
        <div id='loading' style='display: none'>
          Aguarde, Carregado dados...</div>
      </td>
    </tr>
  </table>
    
    <table cellpadding="0" cellspacing="1" border="0" style="">
    <tr style="height:30px">
      <td colspan="5">&nbsp;</td>
    </tr>
    <tr>
      <td colspan="5">
        <div id="fullcalendar" style="width: 400px;"></div>
      </td>
    </tr>
  </table>
  
  <div style="display:block" id="message"></div>
  
</asp:Content>

<asp:Content ID="menu" ContentPlaceHolderID="MenuInternoPlaceholder" runat="server">
  <menu:MenuInterno ID="menuInterno" runat="server" Titulo="Ações" />
</asp:Content>
